import Taro from '@tarojs/taro'
import { API_BASE_URL } from '../../config/env.js'

interface UploadResponse {
  code: number
  message: string
  data?: {
    id: string
    url: string
    name: string
    uploadTime: string
    originalName: string
    fileSize: number
    mimeType: string
  }
  error?: string
}

/**
 * 上传图片到服务器
 * @param filePath 图片本地路径
 * @param name 图片名称，默认为"魔镜测脸"
 * @returns Promise<UploadResponse>
 */
export const uploadImage = async (filePath: string, name: string = '魔镜测脸'): Promise<UploadResponse> => {
  try {
    console.log('开始上传图片:', filePath)
    console.log('上传到:', `${API_BASE_URL}/aiimg/upload`)
    
    const response = await Taro.uploadFile({
      url: `${API_BASE_URL}/aiimg/upload`,
      filePath: filePath,
      name: 'photo', // 这里必须与后端multer配置的字段名一致
      formData: {
        name: name
      },
      header: {
        'Content-Type': 'multipart/form-data'
      }
    })

    console.log('上传响应:', response)

    // 解析响应数据
    const result = JSON.parse(response.data) as UploadResponse
    
    if (response.statusCode === 200 && result.code === 200) {
      console.log('图片上传成功:', result.data)
      return result
    } else {
      throw new Error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    throw error
  }
}

/**
 * 获取用户上传的照片列表
 * @returns Promise<any>
 */
export const getUserPhotos = async () => {
  try {
    const response = await Taro.request({
      url: `${API_BASE_URL}/aiimg/getUserPhotos`,
      method: 'GET'
    })
    return response.data
  } catch (error) {
    console.error('获取照片列表失败:', error)
    throw error
  }
}
